#include <stdio.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#define BUFFER_SIZE 10*1024 // 10K
#define sPORT        1234

int main(void)
{
    char buff[BUFFER_SIZE];
    int n;
    int sockfd; // 服务端套接字(主要用于监听)
    int connfd; // 已连接套接字
    int len;
    struct sockaddr_in server; // 服务端地址数据
    struct sockaddr_in client; // 客户端地址数据

    /* 1. 创建服务端套接字 */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        printf("server socket create failed!\n");
        exit(1);
    }
    printf("server socket create succeful!\n");

    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(sPORT);

    /* 2. 绑定IP+端口 */
    if ((bind(sockfd, (struct sockaddr*)&server, sizeof(server))) != 0) 
    {
        printf("server socket bind failed!\n");
        exit(0);
    }
    printf("socket successfully binded!\n");

    /* 3. 进入监听状态 */
    if ((listen(sockfd, 5)) != 0) 
    {
        printf("listen failed!\n");
        exit(0);
    }
    printf("server listening!\n");

    /* 4. 处理连接请求 */
    len = sizeof(client);
    connfd = accept(sockfd, (struct sockaddr*)&client, &len);
    if (connfd < 0) {
        printf("server acccept failed!\n");
        exit(0);
    }
    printf("server acccept the client!\n");

    /* 5. 通信 */
    while(1)
    {
        bzero(buff, BUFFER_SIZE);

        if (read(connfd, buff, sizeof(buff)) <= 0) {
            printf("client close!\n");
            close(connfd);
            break;
        }
        printf("from client: %s\n", buff);

        // 收到 exit 退出
        if (strncmp("exit", buff, 4) == 0) {
            printf("server exit...\n");
            close(connfd);
            break;
        }
    }

    /* 关闭socket */
    close(sockfd);
    exit(0);


}
